import sys
import time

from DrissionPage import ChromiumPage
import pymysql
import pyautogui
from bs4 import BeautifulSoup
import re


# 获取视频ID，转换为整数
# try:
#     videoid = int(input('从第几条视频开始获取评论: ')) - 1
# except ValueError:
#     print("输入无效，请输入一个整数。三秒后程序自动结束,请重新运行程序")
# time.sleep(6)


# exit(1)


def filter_comment(comment):
    """
    过滤评论中的非法字符
    """
    # 使用正则表达式替换非法字符为空字符串
    filtered_comment = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9.,!?;:()\'"\-_ ]', '', comment)
    return filtered_comment


insert_sql = '''
    UPDATE 抖音视频表
    SET 视频发布时间_2=%s
    WHERE ID = %s
    '''

DB_CONFIG = {
    'host': 'rm-2zea30h4sh8g15zd1ho.mysql.rds.aliyuncs.com',
    'port': 3306,
    'user': "root",
    'password': 'Ds2024@()833429',
    'database': "douyinpinglun"
}
mydb = pymysql.connect(**DB_CONFIG)
cursor = mydb.cursor()
driver = ChromiumPage()
driver.set.window.max()
print('数据库连接成功')
# cursor.execute("select id,视频链接 from 抖音视频表 where id > %s order by id", (videoid,))
cursor.execute(f"select id,视频链接 from 抖音视频表 where 视频发布时间_2 is null ")
videoid_url_tuples = cursor.fetchall()

for videoid_url in videoid_url_tuples:
    # 关联视频表id
    videoid = videoid_url[0]
    print(f'当前正在爬取id为{videoid}的视频')
    # 视频链接
    video_url = videoid_url[1]
    driver.get(video_url)
    driver.wait(5)
    try:
        if driver.ele('x://*[@id="douyin-right-container"]/div[2]/div/div/p[1]').text == '你要观看的视频不存在':
            print('该视频已下架')
            cursor.execute(f'delete from 抖音视频表 where id={videoid}')
            mydb.commit()
            print('事务已提交')
            continue
    except Exception as e:
        video_date_text = driver.ele(
            'xpath://*[@id="douyin-right-container"]/div[2]/div/div/div[1]/div[3]/div/div[2]/div[2]/span').text
        video_date = video_date_text.replace('发布时间：', '')
        print(video_date)

        cursor.execute(insert_sql, (video_date, videoid))
        mydb.commit()
        pass

    try:
        video_date_text = driver.ele(
            'xpath://*[@id="douyin-right-container"]/div[2]/div/div/div[1]/div[3]/div/div[2]/div[2]/span').text
        video_date = video_date_text.replace('发布时间：', '')
    except:
        try:
            driver.ele('.jp8u3iov').click()
            video_date_text = driver.ele('.__VJux97').text
            # 计算日期部分的起始和结束位置
            start_index = video_date_text.find("：") + 1  # 找到“：”的位置，并加1得到日期的起始位置
            end_index = start_index + 10  # 日期长度为10位

            # 使用切片提取日期
            video_date = video_date_text[start_index:end_index]
        except:
            video_date = driver.ele('x://*[@id="video-info-wrap"]/div[1]/div[1]/div[2]/span').text.split('·')
            print(video_date)
    print(video_date)

    cursor.execute(insert_sql, (video_date, videoid))
    mydb.commit()

cursor.close()
mydb.close()
#
# driver.get('https://live.douyin.com/889398542120')
# driver.set.window.max()
